﻿using SheepStorage.Domain.Dto.InputDto;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class LambWeaningService:ILambWeaningService
    {
        private readonly IBaseRepository<LambWeaning> _lambRepository;
        private readonly IBaseRepository<SheepRecord> _recordRepository;
        private readonly IBaseRepository<BuildingManagement> _mentRepository;
        private readonly IBaseRepository<SheepField> _fieldRepository;
        private readonly IBaseRepository<SheepChangeDormitory> _changeRepository;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="lambRepository"></param>
        /// <param name="recordRepository"></param>
        /// <param name="mentRepository"></param>
        /// <param name="fieldRepository"></param>
        /// <param name="changeRepository"></param>
        public LambWeaningService(IBaseRepository<LambWeaning> lambRepository, IBaseRepository<SheepRecord> recordRepository, IBaseRepository<BuildingManagement> mentRepository, IBaseRepository<SheepField> fieldRepository,IBaseRepository<SheepChangeDormitory> changeRepository)
        {
            _lambRepository = lambRepository;
            _recordRepository = recordRepository;
            _mentRepository = mentRepository;
            _fieldRepository = fieldRepository;
            _changeRepository = changeRepository;
        }



        /// <summary>
        /// 羔羊断奶添加
        /// </summary>
        /// <param name="lamb"></param>
        /// <returns></returns>
        public async Task<int> LambWeaningAdd(List<LambWeaning> lambList)
        {
            using (var tran=new TransactionScope())
            {
                try
                {
                    foreach(var lamb in lambList)
                    {
                        //获取档案列表
                        var recordInfo = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(lamb.LambOverbit));

                        recordInfo.SheepRecordGrowth = 2;

                        var mentList = _mentRepository.GetAll().FirstOrDefault(c => c.BuildingManagementId == lamb.TransferToDormitory);
                        recordInfo.BuildingName = mentList.BuildingName;

                        var fieldList = _fieldRepository.GetAll().FirstOrDefault(c => c.SheepFieldId == lamb.DriveField);

                        recordInfo.SheepFieldName = fieldList.SheepFieldName;

                        _recordRepository.Update(recordInfo);

                        DateTime now = DateTime.Now;
                        DateTime weaningTime = lamb.WeaningTime.Value;

                        // 计算日期间隔
                        TimeSpan difference = now - weaningTime;

                        // 获取总天数
                        int weaningdays = (int)difference.TotalDays;


                        var lambWean = new LambWeaning()
                        {
                            LambOverbit = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(lamb.LambOverbit)).OverBit,
                            ElectronicOverbit = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(lamb.LambOverbit)).OverBit,
                            Gender = lamb.Gender,
                            WeaningTime = lamb.WeaningTime,
                            TransferOutDormitory = lamb.TransferOutDormitory,
                            RollOutField = lamb.RollOutField,
                            TransferToDormitory = lamb.TransferToDormitory,
                            DriveField = lamb.DriveField,
                            WeaningWeight = lamb.WeaningWeight,
                            Parity = 2,
                            NursingMotherOverbit = recordInfo.SheepRecordMomOverbit,
                            ElectronicMotherOverbit = recordInfo.SheepRecordMomOverbit,
                            WeaningDays = Math.Abs(weaningdays),
                            AddTime = DateTime.Now,
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            PurchaseSerialNumber = YitIdHelper.NextId().ToString(),
                            IsDel = 0,
                            Remarks = lamb.Remarks,
                        };

                        _lambRepository.Add(lambWean);

                        var changeInfo = new SheepChangeDormitory()
                        {
                            OverBit = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(lamb.LambOverbit)).OverBit,
                            ElEarTag = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(lamb.LambOverbit)).OverBit,
                            ChangedormitoryType = 10,
                            ChangedormitoryDate = DateTime.Now,
                            TransferOutDormitory = lamb.TransferOutDormitory,
                            RollOutField = lamb.RollOutField,
                            TransferToDormitory = lamb.TransferToDormitory,
                            DriveField = lamb.DriveField,
                            Variety = 2,
                            SheepSex = false,
                            Remarks = lamb.Remarks,
                            ChangeState = 0,
                            IsDel = 0,
                        };

                        _changeRepository.Add(changeInfo);
                    }
                    

                    tran.Complete();
                    return 1;
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }



        /// <summary>
        /// 羔羊断奶列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<LambWeaning>> GetLambWeaning(LambWeaningInput input)
        {
            var list = _lambRepository.GetAll().Where(c => c.IsDel == 0).ToList();

            if (!string.IsNullOrEmpty(input.WeanStartDate))
            {
                list = list.Where(c => c.WeaningTime >= DateTime.Parse(input.WeanStartDate)).ToList();
            }

            if (!string.IsNullOrEmpty(input.WeanEndDate))
            {
                list = list.Where(c => c.WeaningTime < DateTime.Parse(input.WeanEndDate).AddDays(1)).ToList();
            }

            if (!string.IsNullOrEmpty(input.LambOverbit))
            {
                list = list.Where(c => c.LambOverbit == input.LambOverbit).ToList();
            }

            if (input.WeanMinDays != null)
            {
                list = list.Where(c => c.WeaningDays >= input.WeanMinDays).ToList();
            }

            if (input.WeanMaxDays != null)
            {
                list = list.Where(c => c.WeaningDays < input.WeanMaxDays).ToList();
            }

            if (input.WeanMinWeight != null)
            {
                list = list.Where(c => c.WeaningWeight >= input.WeanMinWeight).ToList();
            }

            if (input.WeanMaxWeight != null)
            {
                list = list.Where(c => c.WeaningWeight < input.WeanMaxWeight).ToList();
            }

            if (!string.IsNullOrEmpty(input.NursingMotherOverbit))
            {
                list = list.Where(c => c.NursingMotherOverbit == input.NursingMotherOverbit).ToList();
            }

            list=list.OrderByDescending(c=>c.LambWeaningId).ToList();

            return list;
        } 



        /// <summary>
        /// 批量删除/逻辑删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<int> DeleteLambWeaning(params int[] idList)
        {
            if (idList.Length == 0)
            {
                return 0;
            }

            using (var tran=new TransactionScope())
            {
                try
                {
                    var lambWeanList = _lambRepository.GetAll().Where(c => idList.Contains(c.LambWeaningId)).ToList();

                    foreach (var item in lambWeanList)
                    {
                        item.IsDel = 1;
                        item.DelTime = DateTime.Now;
                    };

                    _lambRepository.UpdateRange(lambWeanList);

                    //获取耳号
                    var overbits = lambWeanList.Select(c => c.LambOverbit).ToList();

                    //根据耳号获取数据
                    var recordList = _recordRepository.GetAll().Where(c => overbits.Contains(c.OverBit)).ToList();

                    foreach(var record in recordList)
                    {
                        record.SheepRecordGrowth = 1;
                    }

                    _recordRepository.UpdateRange(recordList);

                    tran.Complete();
                    return lambWeanList.Count;

                }
                catch (Exception)
                {

                    throw;
                }
            }

                
        }



        /// <summary>
        /// 羔羊断奶单个数据
        /// </summary>
        /// <param name="lambWeaningId"></param>
        /// <returns></returns>
        public async Task<LambWeaning> LambWeaningInfo(int lambWeaningId)
        {
            var list = _lambRepository.GetInfoBy(lambWeaningId);

            return list;
        }



        /// <summary>
        /// 羔羊断奶修改
        /// </summary>
        /// <param name="lamb"></param>
        /// <returns></returns>
        public async Task<int> UpdateLambWeaning(LambWeaning lamb)
        {
            lamb.IsDel = 0;
            lamb.DocumentNumber=YitIdHelper.NextId().ToString();
            lamb.PurchaseSerialNumber=YitIdHelper.NextId().ToString();
            lamb.UpdateTime=DateTime.Now;
            lamb.ElectronicOverbit = lamb.LambOverbit;
            lamb.ElectronicMotherOverbit = lamb.NursingMotherOverbit;
            lamb.AddTime = DateTime.Now;

            var result = _lambRepository.Update(lamb);

            return result;
        }



    }
}
